package com.jeremyfeinstein.utils;


import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Environment;
import android.text.Editable;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.widget.EditText;


import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by 75213 on 2017/11/1.
 */

public class Comm {

    public static File getPathFile(String path) {
        String apkName = path.substring(path.lastIndexOf("/"));
        File outputFile = new File(Environment.getExternalStoragePublicDirectory
                (Environment.DIRECTORY_DOWNLOADS), apkName);
        return outputFile;
    }

    public static void rmoveFile(String path) {
        File file = getPathFile(path);
        file.delete();
    }

    public static boolean isAppInstalled(Context context, String packageName) {
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> pinfo = packageManager.getInstalledPackages(0);
        List<String> pName = new ArrayList<String>();
        if (pinfo != null) {
            for (int i = 0; i < pinfo.size(); i++) {
                String pn = pinfo.get(i).packageName;
                pName.add(pn);
            }
        }
        return pName.contains(packageName);
    }

    /**
     * 正则表达式匹配判断
     *
     * @param patternStr 匹配规则
     * @param input      需要做匹配操作的字符串
     * @return true if matched, else false
     */
    public static boolean isMatchered(String patternStr, CharSequence input) {
        Pattern pattern = Pattern.compile(patternStr);
        Matcher matcher = pattern.matcher(input);
        if (matcher.find()) {
            return true;
        }
        return false;
    }

    /**
     * 表情判断
     *
     * @return true if matched, else false
     */
    public static boolean getIsEmoji(char codePoint) {
        if ((codePoint == 0x0) || (codePoint == 0x9) || (codePoint == 0xA)
                || (codePoint == 0xD)
                || ((codePoint >= 0x20) && (codePoint <= 0xD7FF))
                || ((codePoint >= 0xE000) && (codePoint <= 0xFFFD))
                || ((codePoint >= 0x10000) && (codePoint <= 0x10FFFF)))
            return false;
        return true;
    }

    /**
     * 特殊字符判断 (普通)
     *
     * @return true if matched, else false
     */
    public static boolean IsLegitimate(String str, boolean isTitle) {
        if (!TextUtils.isEmpty(str) && str.length() > 0) {
            String strPattern = "";
            if (isTitle) {
                strPattern = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？§№☆★○●◎◇◇◆□△▲■※＃→←↑-]";
            } else {
                strPattern = "[`~@#$%^&|/~@#￥%……&——|§№☆★○●◎◇◇◆□△▲■※＃→←↑]";
            }
            if (Comm.isMatchered(strPattern, str)) {
                return true;
            }
            if (isTitle) {
                if (str.equals(" ") || str.toString().contentEquals("\n")) {
                    return true;
                }
            }
            if (IsEmoji(str)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 特殊字符判断 (登录)
     *
     * @return true if matched, else false
     */
    public static boolean IsLegitimatelogin(String str) {
        if (!TextUtils.isEmpty(str)) {
            if (str.equals(" ") || str.toString().contentEquals("\n")) {
                return true;
            }
            if (IsEmoji(str)) {
                return true;
            }
        }
        return false;
    }


    /**
     * 特殊字符判断 (ip)
     *
     * @return true if matched, else false
     */
    public static boolean IsIP(String str) {
        if (!TextUtils.isEmpty(str)) {
            String strPattern = "[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？§№☆★○●◎◇◇◆□△▲■※＃→←↑-]";
            if (Comm.isMatchered(strPattern, str)) {
                return true;
            }
            String IpPattern = "^((25[0-5]|2[0-4]\\d|[1]{1}\\d{1}\\d{1}|[1-9]{1}\\d{1}|\\d{1})($|(?!\\.$)\\.)){4}$";
            if (!Comm.isMatchered(IpPattern, str)) {
                return true;
            }
            if (str.equals(" ") || str.toString().contentEquals("\n")) {
                return true;
            }
            if (IsEmoji(str)) {
                return true;
            }
        }
        return false;
    }


    private static boolean IsEmoji(String str) {
        if (TextUtils.isEmpty(str) && str.length() > 0) {
            for (int i = 0; i < str.length() - 1; i++) {
                if (Comm.getIsEmoji(str.charAt(i))) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 特殊字符判断 抽取方法 普通输入框
     * IsAll   过滤等级参数   1、全部过滤  2、过滤表情和空格 3、ip过滤
     *
     * @return true if matched, else false
     */
    public static void LegitimateInput(final EditText editText, final int IsAll) {
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String name = s.toString();
                if (!TextUtils.isEmpty(name) && s.length() > 0) {
                    if (IsAll == 3) {
                        if (!getIP(name)) {
                            editText.setError(getPrompt("禁止非IP格式地址"));
                            return;
                        }
                        if (getIpSpecialcharacter(name)) {
                            editText.setError(getPrompt("禁止输入特殊字符"));
                            return;
                        }
                        if (getspace(name)) {
                            editText.setError(getPrompt("禁止输入空格或者换行字符"));
                            return;
                        }
                        if (getemoji(name)) {
                            editText.setError(getPrompt("禁止输入表情字符"));
                            return;
                        }
                    }
                    if (IsAll == 2) {
                        if (getspace(name)) {
                            editText.setError(getPrompt("禁止输入空格或者换行字符"));
                            return;
                        }
                        if (getemoji(name)) {
                            editText.setError(getPrompt("禁止输入表情字符"));
                            return;
                        }
                    }
                    if (IsAll == 1) {
                        if (getSpecialcharacter(name)) {
                            editText.setError(getPrompt("禁止输入特殊字符"));
                            return;
                        }
                        if (getspace(name)) {
                            editText.setError(getPrompt("禁止输入空格或者换行字符"));
                            return;
                        }
                        if (getemoji(name)) {
                            editText.setError(getPrompt("禁止输入表情字符"));
                            return;
                        }
                    }

                    /* String strPattern = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]";
                    if (Comm.isMatchered(strPattern, name)) {
                        editText.setError(getPrompt("禁止输入特殊字符"));
                        return;
                    }
                    if (name.equals(" ") || name.toString().contentEquals("\n")) {
                        editText.setError(getPrompt("禁止输入空格或者换行字符"));
                        return;
                    }
                    for (int i = 0; i < s.length() - 1; i++) {
                        if (Comm.getIsEmoji(s.charAt(i))) {
                            editText.setError(getPrompt("禁止输入表情字符"));
                            return;
                        }
                    }*/
                }
            }
        });
    }

    public static SpannableStringBuilder getPrompt(String prompt) {
        ForegroundColorSpan fgcspan = new ForegroundColorSpan(Color.RED);
        SpannableStringBuilder ssbuilder = new SpannableStringBuilder(prompt);
        ssbuilder.setSpan(fgcspan, 0, prompt.length(), 0);
        return ssbuilder;
    }


    /*
     *   匹配特殊字符
     * */
    public static boolean getSpecialcharacter(String str) {
        String strPattern = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？§№☆★○●◎◇◇◆□△▲■※＃→←↑-]";
        if (Comm.isMatchered(strPattern, str)) {
            return true;
        }
        return false;
    }

    /*
     *   匹配ip
     * */
    private static boolean getIP(String str) {
        String strPattern = "^((25[0-5]|2[0-4]\\d|[1]{1}\\d{1}\\d{1}|[1-9]{1}\\d{1}|\\d{1})($|(?!\\.$)\\.)){4}$";
        if (Comm.isMatchered(strPattern, str)) {
            return true;
        }
        return false;
    }


    /*
     *   匹配特殊字符(ip)
     * */
    private static boolean getIpSpecialcharacter(String str) {
        String strPattern = "[`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？§№☆★○●◎◇◇◆□△▲■※＃→←↑-]";
        if (Comm.isMatchered(strPattern, str)) {
            return true;
        }
        return false;
    }

    /*
     *   匹配空格
     * */
    private static boolean getspace(String str) {
        if (str.contains(" ") || str.contentEquals("\n")) {
            return true;
        }
        return false;
    }

    /*
     *   匹配空格
     * */
    private static boolean getemoji(String str) {
        for (int i = 0; i < str.length() - 1; i++) {
            if (Comm.getIsEmoji(str.charAt(i))) {
                return true;
            }
        }
        return false;
    }


}